    package com.heatup.apt.api.service.impl;

import com.baomidou.framework.service.impl.SuperServiceImpl;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.heatup.apt.api.service.CoachPrivateSortService;
import com.heatup.apt.common.constants.CoachConstants;
import com.heatup.apt.common.dao.CoachPrivateSortMapper;
import com.heatup.apt.common.dao.OrderInfoMapper;
import com.heatup.apt.common.dao.coach.CoachInfoMapper;
import com.heatup.apt.model.CoachPrivateSort;
import com.heatup.apt.model.coach.CoachInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 *
 * CoachPrivateSort 表数据服务层接口实现类
 *
 */
@Service
public class CoachPrivateSortServiceImpl extends SuperServiceImpl<CoachPrivateSortMapper, CoachPrivateSort> implements CoachPrivateSortService {

    private static final Logger log = LoggerFactory.getLogger(CoachPrivateSortServiceImpl.class);

    @Resource
    private CoachPrivateSortMapper coachPrivateSortMapper;

    @Resource
    private CoachInfoMapper coachInfoMapper;

    @Resource
    private OrderInfoMapper orderInfoMapper;

    /**
     * 返回下一个教练 ID
     *
     * 查询用户当前是否已有过私教体验/体测课订单
     * 如果以有则返回之前订单相同的教练ID 否则返回轮排中的下一位教练 ID
     *
     * @param orderId 订单 ID
     * @param userId  用户 ID
     * @return 下一个教练 ID
     * @author blank 2017/8/1 下午3:11
     */
    @Override
    public Integer checkAndReturnNextCoachId(Integer orderId, Integer userId) {

        if (userId == null) {
            throw new RuntimeException("查询用户的教练教练 ID 出错 userId 不能为 空");
        }
        Integer coachId = null;
        // 查询用户的体验/体测 订单
        Integer lastOrderCoachId = orderInfoMapper.queryLastOrderCoachId(userId);
        if (lastOrderCoachId != null) {
            // 返回上次教练 ID
            //查询此教练是否正常上课的状态如不正常返回下一个随机教练
            CoachInfo coachInfo = new CoachInfo();
            coachInfo.setId(lastOrderCoachId);
            coachInfo.setIsPrivate(CoachConstants.CoachSupportStatus.SUPPORT.getIndex());
            coachInfo.setStatus(CoachConstants.CoachStatus.online.getStatus());
            coachInfo = coachInfoMapper.selectOne(coachInfo);
            if (coachInfo == null) {
                //说明教练暂时不能继续上课 继续返回随机教练
                coachId = null;
            } else {
                CoachPrivateSort coachPrivateSort = new CoachPrivateSort();
                coachPrivateSort.setCoachId(coachInfo.getId());
                coachPrivateSort = coachPrivateSortMapper.selectOne(coachPrivateSort);
                //再查询该教练是否在轮排表中
                if (coachPrivateSort != null) {
                    coachId = lastOrderCoachId;
                } else {
                    //如不在表示当前教练暂时不轮排 需要继续返回随机教练
                    coachId = null;
                }
            }
        }
        if (coachId == null) {
            // 先检查教练轮排库是否有数据 PS 第一次发版后数据需要先插入然后直接返回位置1的 coachId
            coachId = checkAndUpdateCoachPrivateSortData();
            if (coachId != null) {
                return coachId;
            }
            // 新私教/体验/体测用户 使用教练轮排
            coachId = coachPrivateSortMapper.queryNextSortCoachId();
            if (coachId != null) {
                return coachId;
            }
        }

        if (coachId == null) {
            throw new RuntimeException("查询用户的教练教练 ID 出错 未查到轮排教练 ID ??? 黑人问号脸 ");
        }
        return coachId;
    }

    /**
     * 更新教练的轮排顺序
     *
     * @param orderId 订单 ID
     * @return true 更新成功 / false 更新失败
     * @throws IllegalArgumentException 当 orderId 为 null 时
     * @author blank 2017/8/1 下午5:42
     */
    @Override
    public Boolean updateCoachSort(Integer orderId) {

        if (orderId == null) {
            throw new IllegalArgumentException("订单ID 不可为空!");
        }
        //查询对应订单的教练 ID
        Integer coachId = orderInfoMapper.queryOrderCoachId(orderId);
        if (coachId != null) {

            //查询教练轮排表
            CoachPrivateSort coachPrivateSort = new CoachPrivateSort();
            coachPrivateSort.setCoachId(coachId);
            coachPrivateSort = coachPrivateSortMapper.selectOne(coachPrivateSort);

            if (coachPrivateSort != null) {
                //判断是否需要更新排序 如果多次下重复单教练 将不更新此教练的排序下标 否则导致查询下次的轮排教练ID接口数据异常


                CoachPrivateSort coachPrivateSortQuery = new CoachPrivateSort();
                coachPrivateSortQuery.setSortNow(coachPrivateSort.getSortNow());
                EntityWrapper<CoachPrivateSort> entityWrapper = new EntityWrapper<>(coachPrivateSortQuery);

                List<CoachPrivateSort> coachPrivateSortList = coachPrivateSortMapper.selectList(entityWrapper);
                boolean r = false;
                if (coachPrivateSortList != null && coachPrivateSortList.size() > 0) {

                    for (CoachPrivateSort privateSort : coachPrivateSortList) {
                        if (privateSort != null
                                && privateSort.getSortNow().equals(coachPrivateSort.getSortNow())
                                && ! privateSort.getCoachId().equals(coachPrivateSort.getCoachId())
                            || privateSort.getSortNow()!= null
                                &&  privateSort.getSortNow() - coachPrivateSort.getSortNow() == 0
                                && privateSort.getCoachId().equals(coachPrivateSort.getCoachId())) {

                            //检查当前教练的 sort_now 与其他 sort_now 相等
                            //OR 当前教练的 sort_now 比其他 sort_now 小 1
                            //相等才+1
                            //更新订单及排序
                            coachPrivateSort.setOrderId(orderId);
                            coachPrivateSort.setSortNow(coachPrivateSort.getSortNow() + 1);
                            coachPrivateSort.setUpdatedTime(new Date());

                            r = coachPrivateSortMapper.updateSelectiveById(coachPrivateSort) > 0;
                            if (r) {
                                log.info("更新教练轮排订单信息及排序成功! ");
                                break;
                            }
                        }
                    }
                }
                if (!r) {
                  throw new RuntimeException("更新教练轮排订单信息及排序失败! ");
                }

                return r;
            }
        }
        return false;


    }

    /**
     * 初始化教练排序表数据
     *
     * @author blank 2017/8/1 下午4:02
     */
    private Integer checkAndUpdateCoachPrivateSortData() {


        Integer coachCount = coachPrivateSortMapper.selectCount(null);
        Integer coachId = null;
        if (coachCount == null || coachCount == 0) {

            //需要初始化教练轮排表数据

            //查询所有在职且支持私教的教练列表
            CoachInfo coachInfoQuery = new CoachInfo();
            coachInfoQuery.setIsPrivate(CoachConstants.CoachSupportStatus.SUPPORT.getIndex());
            coachInfoQuery.setStatus(CoachConstants.CoachStatus.online.getStatus());
            EntityWrapper<CoachInfo> entityWrapper = new EntityWrapper<>(coachInfoQuery);

            List<CoachInfo> coachInfoList = coachInfoMapper.selectList(entityWrapper);
            List<CoachPrivateSort> coachPrivateSortList = new ArrayList<>();

            if (coachInfoList != null && coachInfoList.size() > 0) {

                coachId = coachInfoList.get(0).getId();

                for (int i = 0; i < coachInfoList.size() ; i++) {
                    CoachPrivateSort coachPrivateSort = new CoachPrivateSort();
                    coachPrivateSort.setSortNow(1);//初始化都为1
                    coachPrivateSort.setCoachId(coachInfoList.get(i).getId());
                    coachPrivateSort.setSortNum(i);
                    coachPrivateSort.setCreatedBy(-1);
                    coachPrivateSort.setStatus(1);
                    coachPrivateSort.setCreatedTime(new Date());

                    coachPrivateSortList.add(coachPrivateSort);
                }
            }
            if (coachPrivateSortList != null && coachPrivateSortList.size() > 0) {
                int r = coachPrivateSortMapper.insertBatch(coachPrivateSortList);
                if (r > 0) {
                    log.info("插入初始化教练排序成功! 成功插入 " + r + "条数据");
                }
            }
        }
        return coachId;
    }
}